package com.vgulu.server.common.mongodb;

import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import com.vgulu.server.common.rest.ResourceApi;
import org.bson.Document;
import org.bson.types.ObjectId;

/**
 * Created by wangchunsee on 2017/6/21.
 */
public abstract class MongoRestApi<T extends MongoId> implements ResourceApi<T>{

    @Override
    public T get(String db, String id) {
        return MongoDbUtils.findOne(db,getCol(),Filters.eq("_id",new ObjectId(id)),getDataFactory());
    }

    @Override
    public T create(String db, T bean) {
        Document doc = MongoDbUtils.insertOne(db,getCol(),bean);
        return getDataFactory().createData(doc);
    }

    @Override
    public void update(String db, String id,T bean) {
        bean.setId((ObjectId) null);
        MongoDbUtils.updateOne(db,getCol(), Filters.eq("_id",new ObjectId(id)),bean);
    }

    @Override
    public DeleteResult remove(String db, String id) {
        return MongoDbUtils.deleteOne(db,getCol(), Filters.eq("_id",new ObjectId(id)));
    }
}
